<template>
  <div class="app-container">
    <el-button class=" marginRB10" type="success" @click="allAgree()" plain>批量同意</el-button>
    <el-button class="marginRB10" type="warning" @click="allFreeze()" plain>批量冻结</el-button>
    <el-button class="marginRB10" type="primary" @click="allExport()" plain>导出EXCEL</el-button>

    <el-date-picker class="marginRB10" v-model="listQuery.start_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择起始日期"></el-date-picker>
    <el-date-picker class="marginRB10" v-model="listQuery.end_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束日期"></el-date-picker>

    <el-select filterable v-model="listQuery.status" class="filter-item marginRB10" placeholder='状态' style="width: 200px;">
      <el-option v-for="item in selectList2" :key="item.key" :label="item.lab" :value="item.key"></el-option>
    </el-select>
    <el-input class="marginRB10" v-model="listQuery.search" placeholder="会长ID|公会ID" style="width:200px;" clearable></el-input>
    <el-button type="primary" @click="getList" icon="el-icon-search"   class="marginRB10">搜索</el-button>

    <el-table ref="dataList" :data="menuList" style="margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号" > </el-table-column>
      <el-table-column prop="count_time" label="时间" >
        <template slot-scope="scope">
          {{ dataTime(scope.row.count_time)}}
        </template>
      </el-table-column>
      <el-table-column prop="sociaty_id" label="公会ID" > </el-table-column>
      <el-table-column prop="user_id" label="会长ID" > </el-table-column>
      <el-table-column prop="user_code" label="会长号"> </el-table-column>
      <el-table-column prop="sociaty_name" label="公会名称" > </el-table-column>
      <el-table-column prop="amount" label="房间流水" > </el-table-column>
      <el-table-column prop="real_rate" label="收益比例" > </el-table-column>
      <el-table-column prop="amount" label="应发金币" >
        <template slot-scope="scope">
          {{ (scope.row.amount*scope.row.real_rate)/100}}
        </template>
      </el-table-column>
      <el-table-column prop="rebate" label="金额" >
        <template slot-scope="scope">
          ￥{{ (scope.row.amount*scope.row.real_rate)/10000}}
        </template>
      </el-table-column>
      <el-table-column prop="real_amount" label="实发金币" > </el-table-column>
      <el-table-column prop="uid" label="实发ID" > </el-table-column>
      <el-table-column prop="u_code" label="实发会长号"> </el-table-column>
      <el-table-column prop="status" label="状态" >
        <template slot-scope="scope">
          {{ scope.row.status === 1?'待审核':'' }}
          {{ scope.row.status === 2?'已发放':'' }}
          {{ scope.row.status === 3?'已冻结':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注" > </el-table-column>
      <el-table-column min-width="300" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 1" type="success" size="mini" @click="handleUpdate1(scope.row)" plain>同意</el-button>
          <el-button v-if="scope.row.status === 1" type="warning" size="mini" @click="handleUpdate2(scope.row)" plain>冻结</el-button>
          <el-button v-if="scope.row.status === 3" type="warning" size="mini" @click="handleUpdate5(scope.row)" plain>解冻</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate3(scope.row)" plain>备注</el-button>
          <el-button v-if="scope.row.status !== 2" type="primary" size="mini" @click="handleUpdate4(scope.row)" plain>编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage" @pagination="getList"/>

    <el-dialog v-dialogDrag title="编辑" :visible.sync="dialogFormVisible" @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="时间">
          {{form.count_time}}
        </el-form-item>
        <el-form-item label='公会ID'>
          {{form.sociaty_id}}
        </el-form-item>
        <el-form-item label="公会名称">
          {{form.sociaty_name}}
        </el-form-item>
        <el-form-item label='房间流水'>
          {{form.amount}}
        </el-form-item>
        <el-form-item label="收益比例" prop="real_rate">
          <el-input v-model="form.real_rate" placeholder="请输入收益比例(%)"/>
        </el-form-item>
        <el-form-item label='应发金币'>
          {{(form.amount*form.rate)/100}}
        </el-form-item>
        <el-form-item label="实发金币">
          {{(form.amount*form.real_rate)/100}}
        </el-form-item>
        <el-form-item label='实发ID' prop="uid">
          <el-input v-model="form.uid" placeholder="请输入实发ID"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog v-dialogDrag title="编辑备注" :visible.sync="dialogFormVisible2" @close="handleDialogClose2">
      <el-form ref="dataForm2" :rules="rules2" :model="form2" label-position="right" label-width="140px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="备注">
          <el-input v-model="form2.memo" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible2 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm2()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { saveData, deleteData,  updateData, listData, statisticAgree, statisticFreeze, statisticUnfreeze } from '@/api/unionWater/roomListWater'
  export default {
    data() {
      return {
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          perPage: 10
        },
        selectList2: [{ key: undefined, lab: '全部分类' },{ key: '1', lab: '待审核 ' }, { key: '2', lab: '已发放' }, { key: '3', lab: '已冻结' } ],
        menuList: [],
        dialogFormVisible: false,
        dialogFormVisible2: false,
        dialogStatus: '',
        titleMap: {
          update: '编辑',
          create: '增加'
        },
        form: {
          id: undefined,
          count_time: undefined,
          sociaty_id: undefined,
          sociaty_name: undefined,
          amount: undefined,
          real_rate: undefined,
          real_amount: undefined,
          uid: undefined,
        },
        form2: {
          sociaty_id: undefined,
          memo: undefined,
        },
        rules: {
          real_rate: [{ required: true, message: '请输入收益比例', trigger: 'blur' }],
          uid: [{ required: true, message: '请输入实发ID', trigger: 'blur' },{ len:6, message: '实发ID必须为6个字符', trigger: 'blur' }],
        },
        rules2: {
          memo: [{ required: true, message: '请输入', trigger: 'blur' }],
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        let urlData = '?';
        if(this.listQuery.page){ urlData = urlData + `page=${this.listQuery.page}&`}
        if(this.listQuery.perPage){ urlData = urlData + `perPage=${this.listQuery.perPage}`}
        if(this.listQuery.search){ urlData = urlData + `&search=${this.listQuery.search}`}
        if(this.listQuery.start_at){ urlData = urlData + `&start_at=${this.listQuery.start_at}`}
        if(this.listQuery.end_at){ urlData = urlData + `&end_at=${this.listQuery.end_at}`}
        if(this.listQuery.status){ urlData = urlData + `&status=${this.listQuery.status}`}

        listData(urlData).then(response => {
          this.menuList = response.data.list
          this.total = response.data.meta.total;
          this.listLoading = false
        })
      },
      handleCreate(row) {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate1(row) {
        let data = {ids:JSON.stringify([row.id])}
        statisticAgree(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.submitOk('成功')
          } else {
            this.submitFail('失败')
          }
        })
      },
      handleUpdate2(row) {
        let data = {ids:JSON.stringify([row.id])}
        statisticFreeze(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.submitOk('成功')
          } else {
            this.submitFail('失败')
          }
        })
      },
      handleUpdate5(row) {
        let data = {id:row.id}
        statisticUnfreeze(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.submitOk('成功')
          } else {
            this.submitFail('失败')
          }
        })
      },
      handleUpdate3(row) {
        this.form2 = []
        this.form2.id= row.id
        this.form2.memo= row.memo

        this.dialogFormVisible2 = true

        this.form2 = Object.assign({}, this.form2)
      },
      handleUpdate4(row) {
        this.form = []
        this.form.id= row.id
        this.form.count_time= row.count_time
        this.form.sociaty_id= row.sociaty_id
        this.form.sociaty_name= row.sociaty_name
        this.form.amount= row.amount
        this.form.rate= row.rate
        this.form.real_rate= row.real_rate
        this.form.real_amount= row.real_amount
        this.form.uid= row.uid.toString()

        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        this.form = Object.assign({}, this.form)
      },
      handleDelete(row) {
        let data = {ids:row.id}
        deleteData(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
          }
        })
      },
      allAgree(){
        // this.$refs.dataList.selection)
        let delNum = []
        this.$refs.dataList.selection.forEach((k) => { delNum.push(k.id) })
        if(delNum.length === 0){return;}
        let data = {ids:JSON.stringify(delNum)}
        statisticAgree(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.submitOk('成功')
          } else {
            this.submitFail('失败')
          }
        })
      },
      allFreeze(){
        // this.$refs.dataList.selection)
        let delNum = []
        this.$refs.dataList.selection.forEach((k) => { delNum.push(k.id) })
        if(delNum.length === 0){return;}
        let data = {ids:JSON.stringify(delNum)}
        statisticFreeze(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.submitOk('成功')
          } else {
            this.submitFail('失败')
          }
        })
      },
      submitForm() {
        this.$refs['dataForm'].validate(valid => {
          if(!valid){return}
            let formData = new FormData();
            // for(let item in this.form){this.form[item] === undefined? '':formData.append(item, this.form[item]);}
            formData.append('id', this.form['id'])
            formData.append('uid', this.form['uid'])
            formData.append('rate', this.form['real_rate'])
            saveData(formData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
        })
      },
      submitForm2() {
        this.$refs['dataForm2'].validate(valid => {
          if(!valid){return}
          let formData = new FormData();
          for(let item in this.form2){this.form2[item] === undefined? '':formData.append(item, this.form2[item]);}
          updateData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
              this.dialogFormVisible2 = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
            });
            }
          })
        })
      },
      resetForm() {
        this.form = {
          id: undefined,
          count_time: undefined,
          sociaty_id: undefined,
          sociaty_name: undefined,
          amount: undefined,
          real_rate: undefined,
          real_amount: undefined,
          uid: undefined,
        }
      },
      dataTime(val){
        let oToday = new Date(val);
        let currentDay = oToday.getDay();
        if (currentDay === 0) { currentDay = 7 }
        let mondayTime = oToday.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000;
        let sundayTime = oToday.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000;
        return this.timestampToTime(mondayTime)+'~'+this.timestampToTime(sundayTime)
      },
      timestampToTime(timestamp) {
        let date = new Date(timestamp);
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        let D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        let strDate = Y+M+D;
        return strDate;
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        }
      },
      handleDialogClose2() {
        if (this.$refs['dataForm2']) {
          this.$refs['dataForm2'].clearValidate() // 清除整个表单的校验
        }
      }
    }
  }
</script>
